package org.jash.learnmvp.user;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import org.jash.learnmvp.R;
import org.jash.learnmvp.mvp.BaseActivity;
import org.jash.learnmvp.utils.StoreUtils;

public class CodeLoginActivity extends BaseActivity<ConStruct.ICodeLoginView, CodeLoginPresenter> implements ConStruct.ICodeLoginView {
    private EditText phone;
    private EditText code;
    private Button getCode;

    @Override
    protected int layoutId() {
        return R.layout.activity_code_login;
    }

    @Override
    protected void initData() {
        presenter = new CodeLoginPresenter();
    }

    @Override
    protected void initView() {
        phone = findViewById(R.id.phone);
        code = findViewById(R.id.code);
        getCode = findViewById(R.id.get_code);
        getCode.setOnClickListener(v -> {
            presenter.loadCode(phone.getText().toString());
        });
        findViewById(R.id.login).setOnClickListener(v -> {
            presenter.login(phone.getText().toString(), code.getText().toString());
        });
        findViewById(R.id.logout).setOnClickListener(v -> {
            presenter.logout();
        });
        phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                getCode.setEnabled(s.toString().matches("^(139|138|159|130|185)\\d{8}$"));
            }
        });
    }

    @Override
    public void codeSuccess(int code) {
        this.code.setText("" + code);
    }

    @Override
    public void loginSuccess(String token) {
        Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
        StoreUtils.getInstance().put("token", token);
    }

    @Override
    public void logoutSuccess() {
        Toast.makeText(this, "退出成功", Toast.LENGTH_SHORT).show();
        StoreUtils.getInstance().put("token", null);
    }

    @Override
    public void failure(Throwable throwable) {
        Toast.makeText(this, throwable.getMessage(), Toast.LENGTH_SHORT).show();
        Log.e("TAG", "failure: ", throwable);
    }
}